import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_note/note/base.dart';
import 'package:flutter_note/note/bean.dart';
import 'package:flutter_note/note/const.dart';
import 'package:flutter_note/note/manager.dart';
import 'package:flutter_note/note/page_home.dart';
import 'package:flutter_note/note/utils.dart';
import 'package:flutter_note/note/widgets.dart';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends BaseState<LoginPage> {
  TextEditingController _nameController; //昵称的控制器
  TextEditingController _usernameController; //账号的控制器
  TextEditingController _passController; //密码的控制器
  bool _isLogin = true; //是否为登录状态
  String json = '{"areaCode":"0","channel":"1","data":"{\"accountCategory\":200,\"imei\":\"356156070547799\",\"loginPassword\":\"e10adc3949ba59abbe56e057f20f883e\",\"loginType\":3,\"needSmsVerify\":\"true\",\"userPhone\":\"15699999995\"}","deviceId":"ffffffff-d63f-a834-0000-0000548e560d","display":"1080*1920","imei":"356156070547799","netWorkType":"未知:WIFI","platform":"1","softVersion":"4.2.5","sysVersion":"SM-G9350,8.0.0","token":""}';

  @override
  void initState() {
    super.initState();
    //SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top, SystemUiOverlay.bottom]);
    _initData();
  }

  _initData() async {
    _nameController = TextEditingController();
    _usernameController = TextEditingController();
    _passController = TextEditingController();
    _usernameController.text = await SPUtils.getString(Const.SP_USERNAME);
  }

  @override
  Widget build(BuildContext context) {
    /*SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(
      statusBarColor: c.white, //or set color with: Color(0xFF0000FF)
      systemNavigationBarColor: c.green,
    ));*/
    return Scaffold(
      key: scaffoldkey,
      backgroundColor: color.bg_page,
      body: Stack(
        children: <Widget>[
          Container(
            height: dim.x300,
            color: Colors.white,
          ),
          _account(),
          _title(),
        ],
      ),
    );
  }

  Container _title() {
    return Container(
      margin: EdgeInsets.only(top: dim.x80),
      alignment: Alignment.topCenter,
      child: Text(
        '欢迎来到我的日记',
        style: TextStyle(
            color: color.green, fontSize: dim.t24, fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget _account() {
    return Container(
      margin: EdgeInsets.only(top: dim.x150, left: dim.x30, right: dim.x30),
      alignment: Alignment.topCenter,
      child: Container(
        height: _isLogin ? dim.x300 : dim.x360,
        child: Material(
          color: color.green_light,
          borderRadius: BorderRadius.all(Radius.circular(dim.x2)),
          elevation: dim.x1,
          child: Padding(
            padding: EdgeInsets.only(left: dim.x20, right: dim.x20),
            child: ListView(
              controller: ScrollController(keepScrollOffset: false),
              children: <Widget>[
                _nameTextField(),
                Space(Const.SPACE_TOP, size: _isLogin ? dim.x15 : dim.x30),
                _usernameTextField(),
                Space(Const.SPACE_TOP, size: dim.x30),
                _passwordTextField(),
                Space(Const.SPACE_TOP, size: dim.x30),
                _loginButton(),
                Space(Const.SPACE_TOP),
                Row(
                  children: <Widget>[
                    _registerButton(),
                    //_forgetButton(),//,没做忘记密码这个功能
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _loginButton() {
    return Container(
      //margin: EdgeInsets.only(top: Dim.x380, right: Dim.x60, left: Dim.x60),
      child: Material(
        elevation: dim.x1,
        color: color.green,
        borderRadius: BorderRadius.all(Radius.circular(dim.x150)),
        child: InkWell(
          borderRadius: BorderRadius.all(Radius.circular(dim.x150)),
          onTap: () {
            if (_isLogin) {
              _login();
            } else {
              _register();
            }
          },
          child: Container(
            height: dim.x45,
            alignment: Alignment.center,
            child: Text(
              _isLogin ? '登录' : '注册',
              style: TextStyle(color: Colors.white, fontSize: dim.t16),
            ),
          ),
        ),
      ),
    );
  }

  Widget _registerButton() {
    return Expanded(
      flex: 1,
      child: GestureDetector(
        onTap: () {
          _isLogin = !_isLogin;
          setState(() {});
        },
        child: Container(
          height: dim.x30,
          alignment: Alignment.centerLeft,
          child: Text(
            _isLogin ? '没有账号?注册一个' : '返回登录',
            style: TextStyle(fontSize: dim.t14, color: color.green),
          ),
        ),
      ),
    );
  }

  Widget _forgetButton() {
    return Expanded(
      flex: 1,
      child: GestureDetector(
        onTap: () {},
        child: Container(
          height: dim.x30,
          alignment: Alignment.centerRight,
          child: Text(
            '忘记密码',
            style: TextStyle(fontSize: dim.t14, color: color.green),
          ),
        ),
      ),
    );
  }

  Widget _nameTextField() {
    if (_isLogin) {
      return Container();
    } else {
      return Material(
        color: color.transparent,
        shape: StadiumBorder(
            side: BorderSide(
          color: color.green,
        )),
        child: TextField(
          controller: _nameController,
          keyboardType: TextInputType.text,
          style: TextStyle(fontSize: dim.t16, color: color.txt3),
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: '请输入昵称',
            contentPadding: EdgeInsets.only(
                left: dim.x15, right: dim.x15, top: dim.x10, bottom: dim.x10),
          ),
        ),
      );
    }
  }

  Widget _usernameTextField() {
    return Material(
      color: color.transparent,
      shape: StadiumBorder(
          side: BorderSide(
        color: color.green,
      )),
      child: TextField(
        controller: _usernameController,
        keyboardType: TextInputType.text,
        style: TextStyle(fontSize: dim.t16, color: color.txt3),
        decoration: InputDecoration(
          border: InputBorder.none,
          hintText: '请输入账号',
          contentPadding: EdgeInsets.only(
              left: dim.x15, right: dim.x15, top: dim.x10, bottom: dim.x10),
        ),
      ),
    );
  }

  Widget _passwordTextField() {
    return Material(
      color: color.transparent,
      shape: StadiumBorder(
          side: BorderSide(
        color: color.green,
      )),
      child: TextField(
        controller: _passController,
        keyboardType: TextInputType.text,
        style: TextStyle(fontSize: dim.t16, color: color.txt3),
        obscureText: true,
        decoration: InputDecoration(
          border: InputBorder.none,
          hintText: '请输入密码',
          contentPadding: EdgeInsets.only(
              left: dim.x15, right: dim.x15, top: dim.x10, bottom: dim.x10),
        ),
      ),
    );
  }

  //登录请求
  _login() async {
    if (_usernameController.text.isEmpty) {
      showMessage("用户名是空的");
      return;
    }
    if (_passController.text.isEmpty) {
      showMessage("密码是空的");
      return;
    }
    show();
    var reply = await UserManager.getInstance()
        .login(_usernameController.text, _passController.text);
    dismiss();
    await Future.delayed(Duration(milliseconds: 50), _loginResult(reply));
  }

  _loginResult(Reply reply) {
    if (reply.code == Const.SUCCESS) {
      startToPage(HomePage());
    } else {
      showMessage(reply?.msg);
    }
  }

  //注册请求
  _register() async {
    if (_nameController.text.isEmpty) {
      showMessage("昵称是空的");
      return;
    }
    if (_usernameController.text.isEmpty) {
      showMessage("用户名是空的");
      return;
    }
    if (_passController.text.isEmpty) {
      showMessage("密码是空的");
      return;
    }
    show();
    var reply = await UserManager.getInstance().register(
        _nameController.text, _usernameController.text, _passController.text);
    dismiss();
    showMessage(reply?.msg);
    if (reply.code == Const.SUCCESS) {
      _isLogin = true;
      setState(() {});
    }
  }
}
